package com.xtaller.sdboot.config.interceptor;

import com.xtaller.sdboot.util.CacheUtil;
import com.xtaller.sdboot.utils.bean.JwtModel;
import com.xtaller.sdboot.utils.bean.PermissionModel;
import com.xtaller.sdboot.utils.helper.JsonHelper;
import com.xtaller.sdboot.utils.helper.JwtHelper;
import io.jsonwebtoken.Claims;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @author : Taller
 * @date : 2020/2/29 15:42
 * @Description : 用于继承
 */
public class OriginalFilter implements HandlerInterceptor {
    @Value("${spring.application.name}")
    private String serviceName;

    @Autowired public CacheUtil cacheUtil;
    private final List<String> EXCLUDE_ROUTE = Arrays.asList(
            "swagger-ui.html",
            "/webjars/",
            "/druid/"
    );

    public PermissionModel getByRequest(HttpServletRequest request){
        // 先读取权限表
        var cacheKey = serviceName + "-permission";
        var cache = cacheUtil.getList(cacheKey, PermissionModel.class);
        if(cache == null){
            return null;
        }
        var URL = request.getServletPath();
        var METHOD = request.getMethod().toUpperCase();
        // 找出请求类型一致的
        var pms = cache.stream().filter(x -> x.getMethod().equals(METHOD)).collect(Collectors.toList());
        if(pms.size() == 0){
            return null;
        }
        // 找出相似对应的路由去掉通配符
        AtomicReference<PermissionModel> pm = new AtomicReference<>(new PermissionModel());
        pms.stream().forEach(x -> {
            var tem = x.getUrl().split("\\{");
            if(URL.indexOf(tem[0]) >=0){
                // 完整匹配
                var urs = URL.split("\\/");
                var srs = x.getUrl().split("\\/");
                if(urs.length == srs.length){
                    var check = 0;
                    for(var i = 0; i<srs.length; i++){
                        var sr = srs[i];
                        var ur = urs[i];
                        if(sr.indexOf("{") >=0){
                            check += 1;
                        }else{
                            if(sr.equals(ur)){
                                check += 1;
                            }
                        }
                    }
                    if (check == urs.length) {
                        pm.set(x);
                    }
                }
            }

        });

        return pm.get();
    }

    /**
     * 检测排查路由
     * */
    public Boolean checkRequestUrl(HttpServletRequest request){
        var opt = EXCLUDE_ROUTE.stream().filter(x -> request.getRequestURL().indexOf(x) >= 0).findFirst();
        return opt.isPresent();
    }

    /**
     * 获取缓存中用户的信息
     * */
    public Claims getInfoByToken(String accessToken){
        JwtModel jwt = JwtHelper.validateJWT(accessToken);
        if (!jwt.isSuccess()) {
            return null;
        }
        return jwt.getClaims();
    }

    public String result(int code, String msg){
        var r = JsonHelper.create("code", code)
                .put("msg", msg);
        return JsonHelper.o2s(r);
    }

}
